#import "SetLocationRequest.h"
#import "SetLocationResponse.h"
#import "Status.h"
#import "SoapFault.h"
#import "NSString+Extensions.h"
#import "NSDate+Extensions.h"
#import "SharedPrefs.h"
#import "NGUtility.h"
#import "NGDBHelper.h"

@implementation SetLocationRequest

@synthesize grName;
@synthesize sessionId;
@synthesize location;
@synthesize deviceCode;
@synthesize status;
@synthesize nameValue;
//UYGULAMA_ACILDI gibi durumların UI'ye yansıması için
@synthesize locationUpdatedDelegate; 


- (id) initWithLocation:(NGLocation *)pLocation {
    if (self = [self init]) {
        nameValue = [[[NSMutableDictionary alloc] init] autorelease];
        self.location = pLocation;
        if ([NSString isEmpty:serviceUrl]) {
            serviceUrl = [SharedPrefs getServiceUrl];
        }        
    }
    
    return self;
}


- (id) init {
    if (self = [super init]) {
        self.deviceCode = [NGUtility getDeviceId];
        self.status = HAREKET_EDIYOR;
        //grName = @"YAZILIM";
    }
    return self;
}

- (void) dealloc {
    [location release];
    [deviceCode release];
    [grName release];
    [nameValue release];
    [sessionId release];
    [serviceUrl release];
    [super dealloc];
}

#pragma mark - server post return handler

- (void) setLocationHandler: (id) value {
    
    SetLocationResponse *response  = nil;

	if ([value isKindOfClass:[NSError class]]) {
		NSLog(@"SET LOCATION RESPONSE NSERROR.....%@", value);
        response = [[SetLocationResponse alloc] initWithError:(NSError *)value];
	} else if ([value isKindOfClass:[SoapFault class]]) {
		NSLog(@"SET LOCATION RESPONSE SOAP FAULT.....%@", value);
        response = [[SetLocationResponse alloc] initWithSoapFault:(SoapFault *)value];    
	} else {
        response = [[SetLocationResponse alloc] initWithResponseXml:(NSString *)value];                
    }
    
    NGDBHelper *db = [NGDBHelper openDatabase];
    [db insertLocationForLog:self.location];
    
    if (locationUpdatedDelegate != nil && [locationUpdatedDelegate respondsToSelector:@selector(updated:)]) {
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            [locationUpdatedDelegate updated:self.location];                
        }            
    }

    if(![response isSuccessful]) {
        [db insertLocationForUnsent: self.location];
        NSLog(@"SET LOCATION RESPONSE DB INSERT.....%@", self.location);
    } else {
        //If any message, insert them into database
        NGDBHelper *db = [NGDBHelper openDatabase];
        NSArray *array = [response getMessages];
        [db insertMessages:[response getMessages]];
        if ([array count] > 0) {
            //alert user for incoming messages
            [self alertMessageForMessageArriving:[array count]];
        }
        
        //If any command, change settings according to incoming commands
        [self processCommands:[response getCommands]];        
    }
    
    NSLog(@"SET LOCATION:\n%@", response);
}

/**
 * writes valid	 commands to settings
 */
- (void) processCommands:(NSMutableArray *)commands {
    
    @try {
        for (Command *command in commands) {
            if (![command isUsedForDevice]) {
                continue;
            }
            int value = [command.value intValue]; //TODO validate   int value = tr.com.netgis.util.Command.validate(commandEnum, command.getValue())
            if (command._command == MIN_DISTANCE)
                [SharedPrefs setDeltaDistance:value];
            else if (command._command == MIN_TIME)
                [SharedPrefs setTimeInterval:value];
            else if (command._command == LOCATION_SIZE)
                [SharedPrefs setLocationSize:value];
            else if (command._command == SEND_FREQUENCY)
                [SharedPrefs setSendFrequency:value];
            [SharedPrefs sync];
        }    
    }
    @catch (NSException *exception) {
        NSLog(@"%@", exception);
    }
    @finally {
    }
}



@end
